package com.commerceE.util;

/**
 *=====================================================================
 * Date Utility 
 *
 *---------------------------------------------------------------------
 * Update date  Contents
 *=====================================================================
 * 08/02/2011   create
 *
 */

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import org.apache.log4j.Logger;

public class DateUtil {

	public static SimpleDateFormat sdf_bidStatus = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

	private static Logger mLogger = Logger.getLogger(DateUtil.class.getName());

	 

	/**
	 * Convert date to GMT
	 * 
	 * @param date
	 *            source date
	 * @return Date GMT Date
	 */
	public static Date convertToGmt(Date date) {
		TimeZone tz = TimeZone.getDefault();

		Date retDate = null;
		if ( date != null ) {
			retDate = new Date(date.getTime() - tz.getRawOffset());

			// if we are now in DST, back off by the delta. Note that we are
		    // checking the GMT date, this is the KEY.
		    if (tz.inDaylightTime(retDate)) {
			   Date dstDate = new Date(retDate.getTime() - tz.getDSTSavings());

			   // check to make sure we have not crossed back into standard time
			   // this happens when we are on the cusp of DST (7pm the day before
			   // the change for PDT)
			  if (tz.inDaylightTime(dstDate)) {
				 retDate = dstDate;
			  }
		    }
		}
		return retDate;
	}

	/**
	 * Parse date to string according to specific format
	 * 
	 * @param date
	 * @param sdf
	 * @return
	 */
	public static String parseDateToString(Date date, SimpleDateFormat sdf) {
		if (date == null || sdf == null) {
			return null;
		} else {
			return sdf.format(date);
		}
	}

	/**
	 * Parse a string specific format with to date
	 * 
	 * @param dateStr
	 * @param sdf
	 * @return
	 */
	public static Date parseStringToDate(String dateStr, SimpleDateFormat sdf)  {
		if (dateStr == null || sdf == null) {
			return null;
		} else {
			try {
				return sdf.parse(dateStr);
			} catch (ParseException e) {
				String errMsg = "Can't find parse the '" + dateStr + "' to date' with format" + sdf.toPattern()	+ ".";
				mLogger.error( errMsg);
				return null;
			}
		}
	}

}
